from rest_framework.generics import ListAPIView,CreateAPIView,UpdateAPIView, DestroyAPIView, RetrieveAPIView
from rest_framework.filters import BaseFilterBackend
from rest_framework.response import Response


from api.models import Comment
from api.serializer import *


class CommentFilterBackends(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        article_pk = request.query_params.get('pk')
        return queryset.filter(article_id=article_pk)

# 127.0.0.1:8000/api/v1/comment/?token=61cca770-c8d8-4e8c-b7fa-c3c80e9e7362&pk=1
class CommentView(ListAPIView, CreateAPIView):
    queryset = Comment.objects.all()
    filter_backends = [CommentFilterBackends, ]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return CommentSerializer
        elif self.request.method == 'POST':
            return PostCommentSerializer

    def perform_create(self, serializer):
        user = self.request.user
        article_pk = self.request.query_params.get('pk')
        article_obj = Article.objects.filter(id=article_pk).first()
        comment_obj = serializer.save(user=user, article=article_obj)


# 127.0.0.1:8000/api/v1/comment/1/?token=61cca770-c8d8-4e8c-b7fa-c3c80e9e7362&pk=4
class CommentDetailView(DestroyAPIView):
    queryset = Comment.objects.all()
    filter_backends = [CommentFilterBackends, ]



